//
//  DataBaseHandle.m
//  UI_豆瓣项目
//
//  Created by dllo on 16/1/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "DataBaseHandle.h"
#import "Root1Model.h"
@implementation DataBaseHandle
+ (DataBaseHandle *)sharedDataBaseHandle {
    // 静态修饰指针
    static DataBaseHandle *handle = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[DataBaseHandle alloc] init];
        
    });
    return handle;
}

-(void)openDB {
    // 沙盒路径
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 拼接数据库路径
    NSString *dbPath = [documents stringByAppendingPathComponent:@"Lzy.sqlite"];
    NSLog(@"沙盒：%@",dbPath);
    // 创建数据库
//    sqlite3 * db = nil;
//    
//    sqlite3_open(dbPath.UTF8String, &db);
    int result = sqlite3_open(dbPath.UTF8String, &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"打开成功");
    } else {
        NSLog(@"打开失败");
    }
    
}

- (void)createTable {
    NSString *sqlStr = [NSString stringWithFormat:@"create table if not exists Student(number integer primary key autoincrement, name text)"];
    // 让数据执行SQL语句
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"建表成功");
    } else {
        NSLog(@"建表失败");
    }
    
}


// 删除
- (void)removeModel:(Root1Model *)model {
    // sql语句
    // where 条件删除
    // delete from Student 删除整个表单数据
    // 添加多个条件 用and
    NSString *sqlStr = [NSString stringWithFormat:@"delete from Student where name = '%@'", model.title];
    int result = sqlite3_exec(dbPoint,sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"删除成功");
    } else {
        NSLog(@"删除失败");
    }
    
    
}





// 增加
- (void)insertModel:(Root1Model *)model {
    NSString *sqlStr = [NSString stringWithFormat:@"insert into Student(name) values('%@')", model.title];
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"插入成功");
    }else {
        NSLog(@"插入失败");
}
    
    
    
    
}

- (NSMutableArray *)selectTable {
    
    NSString *sqlStr = [NSString stringWithFormat:@"select * from Student"];
    
    // 创建一个空指针
    sqlite3_stmt *stmt = nil;
    
    // 进入查询
    int result = sqlite3_prepare_v2(dbPoint, sqlStr.UTF8String, -1, &stmt, NULL);
    NSMutableArray *arrModel = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            // 从数据库中取出数据
            const unsigned char *name = sqlite3_column_text(stmt, 1);

            NSString *Str = [NSString stringWithUTF8String:(const char *)name];
            [arrModel addObject:Str];
        }
    }
    
    return arrModel;
}
@end
